package com.movisol.messengercommunicator.asynctasks;

import java.util.ArrayList;
import java.util.List;

import com.movisol.messengercommunicator.controllers.CommunicatorController;
import com.movisol.messengercommunicator.data.CommunicatorRoot;
import com.movisol.messengercommunicator.data.Message;
import com.movisol.messengercommunicator.helper.MessengerCommunicatorHelper;
import com.movisol.messengerprofileservice.controllers.ProfileController;
import com.movisol.messengerprofileservice.helpers.MessengerProfileHelper;
import com.movisol.tools.HelperUtils;

import android.os.AsyncTask;

public class AsyncPostMessage extends AsyncTask<Message, Void, Boolean> {
	
	private ProfileController pc = ProfileController.getInstance();
	private CommunicatorController cc = CommunicatorController.getInstance();

	@Override
	protected Boolean doInBackground(Message... params) {
		
		//Prepare the CommunicatorRoot
		List<Message> list = new ArrayList<Message>();
		list.add(params[0]);
		String signature = MessengerProfileHelper.generateSignature(MessengerCommunicatorHelper.generateSignatureForCommunicatorRoot(list)+HelperUtils.getConfigParam("ChatSecretPhrase", cc.getContext()));
		CommunicatorRoot cr = new CommunicatorRoot();
		cr.setSignature(signature);
		cr.setSku(HelperUtils.getConfigParam("SKU", cc.getContext()));
		cr.setMessages(new ArrayList<Message>());
		cr.getMessages().add(params[0]);

		//Post the message
		String result = cc.postMessage(cr, pc.getUserProfile().getUserId());
		
		CommunicatorRoot messageAnswered = MessengerCommunicatorHelper.parseXMLConversationMessagesListToObject(result);
		cc.setMessageAnswered(messageAnswered);
		if(messageAnswered != null)
		{
//			currentMessagesList.put(messageAnswered.getMessages().get(0).getMessagePublicId(), messageAnswered.getMessages().get(0));
			return true;
		}

		
		return false;
	}

	/* (non-Javadoc)
	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	 */
	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);
		
		if(result)
			cc.fireMessagePosted(null);
		else
		{
			HelperUtils.LogE(getClass(), null);
			cc.fireMessagePosted("Error posting!");
		}
	}

}
